
import { signin } from '@/services/auth/api';
import {
  LockOutlined,
  UserOutlined,
} from '@ant-design/icons';
import {
  LoginForm,
  ProFormCheckbox,
  ProFormText,
} from '@ant-design/pro-components';
import { FormattedMessage, Helmet, history, SelectLang, useIntl, useModel } from '@umijs/max';
import { Alert, message, Tabs } from 'antd';
import { createStyles } from 'antd-style';
import React, { useState } from 'react';
import { flushSync } from 'react-dom';
import Settings from '../../../../config/defaultSettings';
import { removeToke, setToken } from '@/utils/storage';

const useStyles = createStyles(({ token }) => {
  return {
    action: {
      marginLeft: '8px',
      color: 'rgba(0, 0, 0, 0.2)',
      fontSize: '24px',
      verticalAlign: 'middle',
      cursor: 'pointer',
      transition: 'color 0.3s',
      '&:hover': {
        color: token.colorPrimaryActive,
      },
    },
    lang: {
      width: 42,
      height: 42,
      lineHeight: '42px',
      position: 'fixed',
      right: 16,
      borderRadius: token.borderRadius,
      ':hover': {
        backgroundColor: token.colorBgTextHover,
      },
    },
    container: {
      display: 'flex',
      flexDirection: 'column',
      height: '100vh',
      overflow: 'auto',
      position: 'relative',
      '&::before': {
        content: '""',
        position: 'absolute',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        backgroundImage: 'url(/backend.webp)',
        backgroundSize: 'cover',
        backgroundPosition: 'center',
        backgroundRepeat: 'no-repeat',
        filter: 'brightness(0.8)',
        zIndex: -1,
      },
    },
    loginWrapper: {
      display: 'flex',
      flex: 1,
      justifyContent: 'center',
      alignItems: 'center',
      padding: '24px',
    },
    loginFormContainer: {
      minWidth: 400,
      maxWidth: '75vw',
      backgroundColor: 'rgba(255, 255, 255, 0.85)', // 单层半透明背景
      padding: '40px',
      borderRadius: '8px',
      boxShadow: '0 4px 20px rgba(0, 0, 0, 0.15)',
      display: 'flex',
      flexDirection: 'column',
      alignItems: 'center',
    },
    logo: {
      width: 95,
      height: 80,
      marginBottom: 20,
    },
    title: {
      fontSize: '24px',
      fontWeight: 'bold',
      color: '#000',
      marginBottom: '8px',
      textAlign: 'center',
    },
    subtitle: {
      fontSize: '14px',
      color: '#666',
      marginBottom: '32px',
      textAlign: 'center',
    },
  };
});

// const ActionIcons = () => {
//   const { styles } = useStyles();

//   return (
//     <>
//       <AlipayCircleOutlined key="AlipayCircleOutlined" className={styles.action} />
//       <TaobaoCircleOutlined key="TaobaoCircleOutlined" className={styles.action} />
//       <WeiboCircleOutlined key="WeiboCircleOutlined" className={styles.action} />
//     </>
//   );
// };

const Lang = () => {
  const { styles } = useStyles();

  return (
    <div className={styles.lang} data-lang>
      {SelectLang && <SelectLang />}
    </div>
  );
};

const LoginMessage: React.FC<{
  content: string;
}> = ({ content }) => {
  return (
    <Alert
      style={{
        marginBottom: 24,
      }}
      message={content}
      type="error"
      showIcon
    />
  );
};

const Login: React.FC = () => {
  const [userLoginState, setUserLoginState] = useState<API.SigninResult>({});
  const [type, setType] = useState<string>('account');
  const { initialState, setInitialState } = useModel('@@initialState');
  const { styles } = useStyles();
  const intl = useIntl();
  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    if (userInfo) {
      flushSync(() => {
        setInitialState((s) => ({
          ...s,
          currentUser: userInfo,
        }));
      });
    }
  };

  const handleSubmit = async (values: API.LoginParams) => {
    try {
      // 登录
      removeToke()
      const loginResponse = await signin({ ...values, type });
      const { code, data } = loginResponse
      
      if (code == 0) {
        const defaultLoginSuccessMessage = intl.formatMessage({
          id: 'pages.login.success',
          defaultMessage: '登录成功！',
        });
        const { accessToken,type: token_type } = data
        setToken(`bearer ${accessToken}`)
        await fetchUserInfo();
        message.success(defaultLoginSuccessMessage);
        // const urlParams = new URL(window.location.href).searchParams;
        // history.push(urlParams.get('redirect') || '/');
         history.push('/');
        return;
      }
      setErrorMsg(loginResponse.msg || intl.formatMessage({
        id: 'pages.login.failure',
        defaultMessage: '登录失败，请重试！',
      }));
      console.log(loginResponse);
      message.error(errorMsg);
      // 如果失败去设置用户错误信息
      setUserLoginState(loginResponse);
    } catch (error) {
      const defaultLoginFailureMessage = intl.formatMessage({
        id: 'pages.login.failure',
        defaultMessage: '登录失败，请重试！',
      });
      console.log(error);
      message.error(defaultLoginFailureMessage);
    }
  };

  const [errorMsg,setErrorMsg] = useState<string>(intl.formatMessage({
                id: 'pages.login.accountLogin.errorMessage',
                defaultMessage: '账户或密码错误',
              }));
  
  const { code=-1 } = userLoginState;
  const loginType = 'account'
  return (
    <div className={styles.container}>
      <Helmet>
        <title>
          {intl.formatMessage({
            id: "menu.login",
            defaultMessage: "登录页",
          })}
          {Settings.title && ` - ${Settings.title}`}
        </title>
      </Helmet>
      <Lang />
      <div className={styles.loginWrapper}>
        <div className={styles.loginFormContainer}>
          {/* Logo */}
          <img alt="logo" src="/logo.png" className={styles.logo} />

          {/* 标题 */}
          <h2 className={styles.title}>
             {intl.formatMessage({ id: "services.title" ,defaultMessage:"全美卡车订单管理系统"})}
            </h2>

          {/* 副标题 */}
          {/* <p className={styles.subtitle}>快递、供应链、跨境物流服务</p> */}
          <p className={styles.subtitle}>
            {intl.formatMessage({ id: "services.subtitle" ,defaultMessage:"快递、供应链、跨境物流服务"})}
          </p>

          {/* 登录表单 */}
          <div style={{ width: "100%" }}>
            <LoginForm
              contentStyle={{
                width: "100%",
                margin: 0,
                padding: 0,
                backgroundColor: "transparent", // 表单背景透明
              }}
              // initialValues={{
              //   username: 'T_0002',
              //   autoLogin: true,
              // }}
              submitter={{
                searchConfig: {
                  submitText: intl.formatMessage({
                    id: "login.submitText",
                    defaultMessage: "登录",
                  }),
                },
              }}
              onFinish={async (values) => {
                await handleSubmit(values as API.LoginParams);
              }}
            >
              <ProFormText
                name="username"
                fieldProps={{
                  size: "large",
                  prefix: <UserOutlined />,
                }}
                placeholder={intl.formatMessage({
                  id: "login.username.placeholder",
                  defaultMessage: "请输入用户名",
                })}
                rules={[
                  {
                    required: true,
                    message: intl.formatMessage({
                      id: "login.username.required",
                      defaultMessage: "请输入用户名!",
                    }),
                  },
                ]}
              />
              <ProFormText.Password
                name="password"
                fieldProps={{
                  size: "large",
                  prefix: <LockOutlined />,
                }}
                placeholder={intl.formatMessage({
                  id: "login.password.placeholder",
                  defaultMessage: "请输入密码",
                })}
                rules={[
                  {
                    required: true,
                    message: intl.formatMessage({
                      id: "login.password.required",
                      defaultMessage: "请输入密码！",
                    }),
                  },
                ]}
              />

              <div style={{ marginBottom: 24 }}>
                <ProFormCheckbox noStyle name="autoLogin">
                  {intl.formatMessage({
                    id: "login.autoLogin",
                    defaultMessage: "自动登录",
                  })}
                </ProFormCheckbox>
              </div>
            </LoginForm>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Login;
